import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_widget_from_html/flutter_widget_from_html.dart';
import 'package:get/get.dart';
import 'package:sinosheets/components/NetWorkImage/NetworkImageWidget.dart';
import 'package:sinosheets/main_config.dart';
import 'package:sinosheets/route/route_utils.dart';

import 'logic.dart';

class ProductDetailPage extends StatefulWidget {
  const ProductDetailPage({Key? key}) : super(key: key);

  @override
  State<ProductDetailPage> createState() => _ProductDetailPageState();
}

class _ProductDetailPageState extends State<ProductDetailPage> {
  final ProductDetailLogic logic = Get.put(ProductDetailLogic());

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ProductDetailLogic>(builder: (get) {
      return Scaffold(
        backgroundColor: const Color(0xFFF7F8FA),
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: const Text(
            'Product Detail',
            style: TextStyle(
              color: Colors.black87,
              fontSize: 18,
              fontWeight: FontWeight.bold,
            ),
          ),
          centerTitle: true,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.black87),
            onPressed: () => Get.back(),
          ),
          actions: [
            //收藏按钮
            IconButton(
              icon: Icon(get.isFavorite ? Icons.favorite : Icons.favorite_border, color: get.isFavorite ? Colors.red : Colors.black87),
              onPressed: () => get.collectProduct(),
            ),
          ],
        ),
        body: Column(
          children: [
            Expanded(
                child: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 商品图片区域
                  _buildProductImage(),

                  // 商品信息区域
                  _buildProductInfo(),

                  // 价格区域
                  _buildPriceSection(),

                  // 销售信息区域
                  get.isFlashSale ? SizedBox() : _buildSalesInfo(),

                  // 店铺信息区域
                  get.isFlashSale ? SizedBox() : _buildShopInfo(),

                  ///商品描述区域
                  _buildProductDescription(),
                  // 商品详情区域
                  get.detailHtml.isEmpty ? SizedBox() : _buildProductDetail(),
                ],
              ),
            )),

            // 操作按钮区域
            _buildActionButtons(),
          ],
        ),
      );
    });
  }

  /// 构建商品图片区域
  Widget _buildProductImage() {
    return Container(
      width: double.infinity,
      height: 300.r,
      color: Colors.white,
      child: NetworkImageWidget(
        url: logic.productInfo['img'] ?? '',
        fit: BoxFit.cover,
      ),
    );
  }

  /// 构建商品信息区域
  Widget _buildProductInfo() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.r),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 商品名称
          Text(
            logic.productInfo['itemName'] ?? '',
            style: TextStyle(
              fontSize: 18.r,
              fontWeight: FontWeight.bold,
              color: Colors.black87,
            ),
            maxLines: 3,
            overflow: TextOverflow.ellipsis,
          ),

          SizedBox(height: 12.r),

          // 商品ID
          GestureDetector(
            onTap: () {
              Clipboard.setData(ClipboardData(text: "${logic.productInfo['inId']}"));
              Get.snackbar('Copy Success', 'Product ID has been copied to the clipboard', snackPosition: SnackPosition.BOTTOM);
            },
            child: Row(
              children: [
                Text(
                  'Product ID: ${logic.productInfo['inId'] ?? ''}',
                  style: TextStyle(
                    fontSize: 12.r,
                    color: Colors.grey,
                  ),
                ),
                SizedBox(width: 4.r),
                //复制
                Icon(Icons.copy, size: 14.r, color: Colors.grey),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建价格区域
  Widget _buildPriceSection() {
    double currentPrice = (logic.productInfo['price'] ?? 0.0).toDouble();
    double originalPrice = (logic.productInfo['crossedPrice'] ?? 0.0).toDouble();
    String symbol = logic.productInfo['symbol'] ?? 'USD';

    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.r),
      color: Colors.white,
      margin: EdgeInsets.only(top: 8.r),
      child: Row(
        children: [
          // 当前价格
          Text(
            '${currentPrice.toStringAsFixed(2)}$symbol',
            style: TextStyle(
              fontSize: 24.r,
              fontWeight: FontWeight.bold,
              color: const Color(0xFFFF6B6B),
            ),
          ),

          SizedBox(width: 12.r),

          // 原价（划线）
          if (originalPrice > currentPrice)
            Text(
              '${originalPrice.toStringAsFixed(2)}$symbol',
              style: TextStyle(
                fontSize: 16.r,
                color: Colors.grey,
                decoration: TextDecoration.lineThrough,
              ),
            ),

          const Spacer(),

          // 折扣百分比
          if (originalPrice > currentPrice)
            Container(
              padding: EdgeInsets.symmetric(horizontal: 8.r, vertical: 4.r),
              decoration: BoxDecoration(
                color: const Color(0xFFFF6B6B),
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Text(
                '-${((originalPrice - currentPrice) / originalPrice * 100).toStringAsFixed(0)}%',
                style: TextStyle(
                  fontSize: 12.r,
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
        ],
      ),
    );
  }

  /// 构建销售信息区域
  Widget _buildSalesInfo() {
    int saleNum = logic.productInfo['saleNum'] ?? 0;

    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.r),
      color: Colors.white,
      margin: EdgeInsets.only(top: 8.r),
      child: Row(
        children: [
          Icon(Icons.shopping_cart, color: Colors.grey[600], size: 20.r),
          SizedBox(width: 8.r),
          Text(
            'Sales: $saleNum',
            style: TextStyle(
              fontSize: 14.r,
              color: Colors.grey[600],
            ),
          ),
          const Spacer(),
          Text(
            'Source: ${_getSourceTypeText(logic.productInfo['sourceType'])}',
            style: TextStyle(
              fontSize: 14.r,
              color: Colors.grey[600],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建店铺信息区域
  Widget _buildShopInfo() {
    String shopId = logic.productInfo['shopId'] ?? '';

    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.r),
      color: Colors.white,
      margin: EdgeInsets.only(top: 8.r),
      child: Row(
        children: [
          Container(
            width: 40.r,
            height: 40.r,
            decoration: BoxDecoration(
              color: const Color(0xFF4CAF50),
              borderRadius: BorderRadius.circular(20.r),
            ),
            child: const Icon(
              Icons.store,
              color: Colors.white,
              size: 20,
            ),
          ),
          SizedBox(width: 12.r),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  'Shop ID: $shopId',
                  style: TextStyle(
                    fontSize: 14.r,
                    fontWeight: FontWeight.w600,
                    color: Colors.black87,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  ///商品描述区域
  Widget _buildProductDescription() {
    //如果attr字段不为空，则显示attr字段
    if (logic.productInfo['attr'] != null) {
      return Container(
        width: double.infinity,
        padding: EdgeInsets.all(16.r),
        color: Colors.white,
        child: Text(logic.productInfo['attr'] ?? ''),
      );
    } else {
      return SizedBox();
    }
  }

  ///商品信息区域
  Widget _buildProductDetail() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.r),
      margin: EdgeInsets.only(top: 8.r),
      color: Colors.white,
      child: HtmlWidget(logic.detailHtml),
    );
  }

  /// 构建操作按钮区域
  Widget _buildActionButtons() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.all(16.r),
      color: Colors.white,
      margin: EdgeInsets.only(top: 8.r),
      child: Row(
        children: [
          // 查看详情按钮
          if (logic.productInfo['detailUrl'] != null)
            Expanded(
              child: ElevatedButton(
                onPressed: () => _viewDetail(),
                style: ElevatedButton.styleFrom(
                  backgroundColor: const Color(0xFF4CAF50),
                  padding: EdgeInsets.symmetric(vertical: 12.r),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(8.r),
                  ),
                ),
                child: Text(
                  'View Detail',
                  style: TextStyle(
                    fontSize: 16.r,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ),

          if (logic.productInfo['detailUrl'] != null) SizedBox(width: 12.r),

          // 购买按钮
          Expanded(
            child: ElevatedButton(
              onPressed: () => _buyNow(),
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFFF6B6B),
                padding: EdgeInsets.symmetric(vertical: 12.r),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(8.r),
                ),
              ),
              child: Text(
                'Buy Now',
                style: TextStyle(
                  fontSize: 16.r,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 获取来源类型文本
  String _getSourceTypeText(String? sourceType) {
    switch (sourceType) {
      case 'wd':
        return 'Weidian';
      case 'tb':
        return 'Taobao';
      case 'jd':
        return 'JD';
      case 'pdd':
        return 'Pinduoduo';
      default:
        return 'Other';
    }
  }

  /// 查看详情
  void _viewDetail() {
    String detailUrl = logic.productInfo['detailUrl'] ?? '';
    if (detailUrl.isNotEmpty) {
      RouteUtils.toWebView(url: detailUrl);
    }
  }

  /// 立即购买
  void _buyNow() {
    if (logic.isFlashSale) {
      RouteUtils.toWebView(url: "${AppPrefix.urlPrefix}/chooseSku?id=${logic.productInfo['id']}");
    } else {
      String detailUrl = logic.productInfo['detailUrl'] ?? '';

      RouteUtils.toWebView(url: "${AppPrefix.urlPrefix}/product-detail?url=${Uri.encodeComponent(detailUrl)}");
    }
  }

  @override
  void dispose() {
    Get.delete<ProductDetailLogic>();
    super.dispose();
  }
}
